<?php
namespace control;
/*
*销售单类
*/

class assetApplyClass extends adIndexClass
{
    private const page = 'assetApply';
    private const table = 'asset_purchase';
    private const tableMx = 'asset_purchase_detail';
    private const title = '资产申购';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "申请单号",
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'staffId'  => [
                        'name'  => '申请人',
                        'width' => 250,
                    ],
                    'deptName'         => [
                        'name'  => '申请人部门',
                        'width' => 300,
                    ],
                    'money'          => [
                        'name'  => '预计金额',
                        'width' => 250,
                    ],
                    'recordDate'          => [
                        'name'  => '申请日期',
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 250,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "部门名称"   => text(array("name" => "deptName")),
                    '申请人' => selectMultiple(["name" => "staffId", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                ],
                [
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
            "deptName" => $this->post('deptName'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),
            "staffId" => $this->post('staffId'),
            'coid' => self::$coid,
        );
        $and = $this->seeSelf(self::page);
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "recordDate desc,orderNo desc"));
        $json['sql'] = $page['sql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => $array['state'] =='草稿'?array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"):[],
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            if ($array['state'] == '已通过') {
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'staffId':
                        $row[] = self::findStaff($array['staffId']);
                        break;
                    case 'money':
                        $money = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]'", 'sum' => "money"));
                        $row[] = $money;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx,
            'single' => " orderId in (select id from ".self::table." where 1=1 {$where}) ",
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'money'        => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $tr[] = ['', '名称', '用途描述', '预计采购数量', '预计采购单价', '预计采购金额', '备注'];
        $result = find(array(
            'field' => "id as mxId,name,description,num,price,money as rowMoney,text as mxText",
            'table' => self::tableMx." where orderId = '$info[id]' order by list"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $tr[] = $this->listRow($array);
            }
        }else{
            $tr[] = $this->listRow(['mxId'=>self::getId(), 'list'=>1]);
        }
        $total = find(array('table'=>self::tableMx,'single'=>"orderId = '$info[id]'",'field'=>"ifnull(sum(num),0) as num,ifnull(sum(money),0) as money"));
        $total_tr = [
            3 => "<span id='numTotal'>".self::lostZero($total['num'], 'numPrecision')."</span>",
            5 => "<span id='moneyTotal'>".self::lostZero($total['money'])."</span>",
        ];
        $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total_tr));

        $deptName = $info['deptName']?:departmentClass::getTypeName($this->controlJob['departmentId']);
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "申请人：" => selectMultiple(["name" => "staffId",'change'=>'getDepartment', "value" => $info['staffId'] ?: self::$stid, 'table' => "staff", 'where' => "state != '离职'", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => '请选择']),
                    must . "申请部门：" => "<span id='deptName'>" . $deptName . "</span>",
                    must . "申请日期：" => text(array('name' => 'recordDate', 'laydate' => [], 'value' => $info['recordDate'] ?: $this->date))

                ],
                [
                    "申请事由：" => text(["name" => "text", 'class' => 'long', "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '明细',
            'html' => $list,
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= $this->editJs();
        //返回
        return $this->tab($data);
    }

    /**
     * Desc : 明细
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function listRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $mxId = isset($data['mxId'])&&$data['mxId']?$data['mxId']:self::getId();
        $field = ['name', 'description', 'num', 'price', 'rowMoney', 'mxText'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'listRow',
            'copy' => ['name', 'description', 'num', 'price', 'mxText'],
            'nodeTextByClass' => ['rowMoney'],
        ],320);
        $delArg = json_encode([
            'empty' => ['name', 'description', 'num', 'price', 'mxText'],
            'emptyByClass' => ['rowMoney'],
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg);countMoney(this)","cloneRows(this,$cloneArg);countMoney(this)", "addRow(this);countMoney(this)"),
            hidden(array('name' => 'mxId[]', 'value' => $mxId)) .
            text(array('name' => 'name[]', 'value' => $array['name'])),
            text(array('name' => 'description[]', 'value' => $array['description'])),
            text(array('name' => 'num[]', 'type' => 'number', 'blur' => 'countMoney', 'value' => $array['num'])),
            text(array('name' => 'price[]', 'type' => 'number', 'blur' => 'countMoney', 'value' => $array['price'])),
            "<span class='rowMoney'>$array[rowMoney]</span>",
            text(array('name' => 'mxText[]', 'class' => 'text', 'value' => $array['mxText'])),
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     *添加一行
     */
    public function addRow()
    {
        $res = json_decode($this->listRow(),true);
        $json['data'] = $res['html'];
        return json_encode($json, 320);
    }

    public function editJs(): string
    {
        return <<<eof
<script>
function getDepartment(e){
    let val = $(e).val();
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getDepartment',{value:val},function(res) {
          $("#deptName").html(res.html);
    },'json');
}
function addRow(e){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{},function(res) {
        $(e).closest('tr').after(res.data);
        resetNumber($(e).closest('tbody'))
    },'json');
}
//通过单价计算金额，税额等
function countMoney(e){
    let trObj = $(e).parent().parent();
    countProcess(trObj)
}
function countProcess(trObj){
    let price = trObj.find("[name='price[]']").val();
    let num = trObj.find("[name='num[]']").val();
    let money;
    money = (Number(price)*Number(num)).toFixed(2);
    trObj.find(".rowMoney").html(money);
    countTotal();
}
function countTotal(){
    let price,num;
    let numTotal = 0;
    let money=0;
    $("[name='num[]']").each(function() {
        num = Number($(this).val());
        price = Number($(this).parent().parent().find("[name='price[]']").val());
        console.log(price)
        money+=num*price;
        numTotal+=num;
    })
    $("#moneyTotal").html(money.toFixed(2))
     $("#numTotal").html(numTotal)
}
</script>
eof;
    }


    /**
     * 获取部门
     */
    public function getDepartment(): bool|string
    {
        $id = $this->post('value');
        $staff = query('staff',"stid = '$id'");
        $job = query('job',"id = '$staff[jobId]'");
        $json['html'] =departmentClass::getTypeName($job['departmentId']);
        return json_encode($json, 320);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId') ?: [];
        $numArr = $this->post('num');
        $priceArr = $this->post('price');
        $mxTextArr = $this->post('mxText');
        $nameArr = $this->post('name');
        $descriptionArr = $this->post('description');
        $field = [
            'staffId' => $this->post('staffId'),
            'text' => $this->post('text'),
            'recordDate' => $this->post('recordDate'),
        ];
        $annotation = [
            'staffId' => '申请人',
            'recordDate' => '单据日期',
        ];
        $rules = [
            'staffId' => 'required',
            'recordDate' => 'required|date',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        }  elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请添加明细';
        } elseif (static::is_null_array($nameArr)) {
            $json['warn'] = '请填写名称';
        } elseif (static::is_null_array($numArr)) {
            $json['warn'] = '数量请填写完整';
        } elseif (static::is_null_array($priceArr)) {
            $json['warn'] = '价格请填写完整';
        } elseif (!empty($info['id']) && $info['state'] != '草稿') {
            $json['warn'] = '此单据不是草稿状态，不能修改';
        } else {
                $this->startTrans();
                $staff = query('staff',"stid = '$field[staffId]'");
                $job = query('job',"id = '$staff[jobId]'");
                $field['deptName'] = departmentClass::getTypeName($job['departmentId']);
                if (!$info['id']) {
                    $userNo = codeTemplateClass::generateCode(self::page, [
                        'prefix' => 'ZCSG' . date('Ymd', strtotime($field['recordDate'])),
                        'table' => self::table,
                        'field' => 'orderNo',
                        'where' => " and coid = '" . self::$coid . "'",
                    ], $field);
                    $field = array_merge($field, [
                        'id' => $id,
                        'orderNo' => $userNo,
                        'state' => '草稿',
                        'coid' => self::$coid,
                        'stid' => $this->control['stid'],
                    ]);
                    $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
                } else {
                    $json['warn'] = static::update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => $where,
                    ]);
                }

                //添加或更新明细
                if (is_array($mxIdArr)) {
                    foreach ($mxIdArr as $k => $nid) {
                        $mx = query(self::tableMx, "id = '$nid'");
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::tableMx,
                                "field" => [
                                    'name' => $nameArr[$k],
                                    'description' => $descriptionArr[$k],
                                    'num' => $numArr[$k],
                                    'price' => $priceArr[$k],
                                    'money' => $numArr[$k]*$priceArr[$k],
                                    'text' => $mxTextArr[$k],
                                ],
                                "where" => " id = '$nid'",
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::tableMx,
                                "field" => [
                                    'id' => $nid,
                                    'orderId' => $id,
                                    'coid' => self::$coid,
                                    'name' => $nameArr[$k],
                                    'description' => $descriptionArr[$k],
                                    'num' => $numArr[$k],
                                    'price' => $priceArr[$k],
                                    'money' => $numArr[$k]*$priceArr[$k],
                                    'text' => $mxTextArr[$k],
                                ],

                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }
                if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                    $this->commitTrans();
                    delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn'] = 2;
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                } else {
                    $this->rollback();
                }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '资产申购',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun'=>'',
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun'=>'',
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }
    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $button = [];
            //审核按钮
            $button = array_merge($button, $this->auditButton($info));
            if ($info['state'] =='草稿'){
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑用户",
                        "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                    ];
                }
                if ($this->power(self::page,'del')){
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }

            $audit = query('audit',"targetId = '$info[id]'");

            $tr[] = ['名称', '用途描述', '预计采购数量', '预计采购单价', '预计采购金额', '备注'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $tr[] = [
                    $array['name'],
                    $array['description'],
                    $array['num'],
                    $array['price'],
                    $array['money'],
                    $array['text'],
                ];
            }
            $total = find(array('table' => self::tableMx, 'field' => "sum(any_value(num)) as num,sum(any_value(money)) as totalMoney", 'single' => "orderId = '$info[id]' group by orderId"));
            $total['num'] = $total['num'] ?? 0;
            $total['totalMoney'] = $total['totalMoney'] ?? 0;
            $total_tr = [
                    2=>$total['num'],
                    4=>$total['totalMoney']
                ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '基本信息' => array(
                    array(
                        "申请人部门" => $info['deptName'],
                        "申请人" => self::findStaff($info['staffId']),
                        "申请日期" => $info['recordDate'],
                        "单据编号" => $info['orderNo'],
                    ),
                    array(
                        "制单人" => self::findStaff($info['stid']),
                        "状态" => $info['state']
                    ),
                    array(
                        "申请事由" => pre($info['text']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '明细',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailBlock([
                '流程' => auditClass::auditRecord(self::table, $info['id'])
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = "删除失败：不是草稿状态，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog","where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow","where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message","where" => " typeid = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}

